package com.xms.webresource.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.webresource.api.model.UpdateWebResourceModel;
import com.xms.webresource.entity.WebResource;
import com.xms.webresource.service.IWebResourceContentCoder;
import com.xms.webresource.service.IWebResourceFinderService;
import com.xms.webresource.service.IWebResourceUpdaterService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

/**
 * <p>
 * WebResourceUpdaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/19
 */
@RestController
@RequestMapping("{org}/api/webresource")
public class WebResourceUpdaterController extends ApiBaseController {
    private IWebResourceFinderService _webResourceFinderService;
    private IWebResourceUpdaterService _webResourceUpdaterService;
    private IWebResourceContentCoder _webResourceContentCoder;
    @Autowired
    public WebResourceUpdaterController(IWebResourceFinderService webResourceFinderService,
                                        IWebResourceUpdaterService webResourceUpdaterService,
                                        IWebResourceContentCoder webResourceContentCoder)
    {
        _webResourceFinderService = webResourceFinderService;
        _webResourceUpdaterService = webResourceUpdaterService;
        _webResourceContentCoder = webResourceContentCoder;
    }

    @ApiOperation("修改Web资源")
    @PostMapping("update")
    public JsonResultObject update(@RequestBody UpdateWebResourceModel model) throws UnsupportedEncodingException, XmsException, SQLException {
        if(UUIDUtil.isEmpty(model.webresourceid) || StringUtil.isEmpty(model.name) || StringUtil.isEmpty(model.content)){
            return JNotSpecifiedParams("id", "name", "content");
        }
        WebResource entity = _webResourceFinderService.getById(model.webresourceid);
        if(entity == null){
            return JNotFound();
        }
        entity.setName(model.name);
        entity.setContent(_webResourceContentCoder.encode(model.content));
        entity.setDescription(model.description);
        return _webResourceUpdaterService.update(entity) ?
                JUpdateSuccess() : JUpdateFailure();
    }
}
